<template>
    <div class="json-parse-container">
        <h2 class="json-parse-title">JSON格式化</h2>
        <div class="json-parse-content">
            <div class="json-parse-btns">
                <button class="json-parse-btn" @click="formatText">格式化</button>
                <button class="json-parse-btn" @click="compact">压缩</button>
                <button class="json-parse-btn" @click="deslash">去转义</button>
            </div>
            <textarea class="json-parse-input" v-model="inputText" placeholder="请输入json数据..."></textarea>


            <div class="json-parse-result">
                <span class="json-parse-result-fail" v-if="showFail">JSON解析失败</span>
                <span class="json-parse-result-success" v-if="!showFail&&inputText!==''">JSON解析通过</span>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: "JsonParseUtil",
    data() {
        return {
            inputText: '',
        }
    },
    computed: {
        showFail: function () {
            if (!this.inputText || this.inputText === '') {
                return false;
            }
            try {
                JSON.parse(this.inputText)
            } catch (e) {
                return true;
            }
        },
    },
    methods: {
        //格式化
        formatText() {
            const parsedJson = JSON.parse(this.inputText);
            this.inputText = JSON.stringify(parsedJson, null, 2);
        },
        //压缩
        compact() {
            this.inputText = this.inputText.replace(/\s+/g, '')
        },
        //去斜杠
        deslash() {
            this.inputText = this.inputText.replaceAll('\\', '')
        },
    },
}
</script>

<style scoped>
.json-parse-container {
    width: 100vw;
    height: 100vh;
    display: flex;
    background-color: #a5a2a2;
    justify-content: center;
    align-items: center;
}

.json-parse-title {
    position: absolute;
    top: 0;
    margin: 0;
}

.json-parse-content {
    position: relative;
    width: 90%;
    height: 90%;
    background-color: #d5d2d2;
    box-shadow: 0 0.25rem 1.125rem rgba(76, 92, 70, 0.1);
    border-radius: 5px;
}

.json-parse-btns {
    padding: 8px;
    margin: 2px;
    border-bottom: #a5a2a2 2px solid;
    display: flex;
    gap: 5px;
}

.json-parse-btn {
    background-color: transparent;
    border: #6365e1 3px solid;
    cursor: pointer;
}

.json-parse-btn:hover {
    background-color: #82d5d7;
    scale: 1.1;
}

.json-parse-input {
    height: 70%;
    width: 99%;
    font-size: 1.5rem;
    resize: none;
    margin: 5px;
    border-radius: 5px;
    overflow-wrap: break-word;
    text-align: start;
}

.json-parse-result {
    height: 20%;
    width: 99%;
    margin: 10px;
    border-radius: 5px;
    background-color: #fff;
}

.json-parse-result-fail {
    color: red;
    font-size: 2rem;
    font-weight: 800;
}
.json-parse-result-success{
    color: greenyellow;
    font-size: 2rem;
    font-weight: 800;
}
</style>